#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "../../dprint.h"

#include "imc_memcached.h"

/**
 * Connect to the Memcached server
 */
int memcached_setup(int * p_sockfd, str remote_memcached_ip, int remote_memcached_port)
{/*{{{*/
    if(NULL == p_sockfd)
    {
        return -1;
    }
    
    int sockfd = -1;
    struct sockaddr_in address = {0};
    int result = -1;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    address.sin_family      = AF_INET;
    address.sin_addr.s_addr = inet_addr(remote_memcached_ip.s);
    address.sin_port        = htons(remote_memcached_port);
 
    result = connect(sockfd, (struct sockaddr *)&address, sizeof(address));

    if(-1 == result)
    {
        LM_ERR("Connect to the Memcached Server[%.*s:%d]!\n",remote_memcached_ip.len, remote_memcached_ip.s,remote_memcached_port);
        return -1;
    }

    *p_sockfd = sockfd;

    return 0;
}/*}}}*/


void memcached_close(int sockfd)
{/*{{{*/
    close(sockfd);
}/*}}}*/

int memcached_command(int sockfd, str* send_buf, str* recv_buf)
{/*{{{*/
    int len = -1;
    
    if(NULL == send_buf || NULL == send_buf->s || 0 >= send_buf->len 
        || NULL == recv_buf || NULL == recv_buf->s || 0 >= recv_buf->len)
    {
        return -1;
    }

    send(sockfd, send_buf->s, send_buf->len, 0);
    len = read(sockfd, recv_buf->s, recv_buf->len);
    recv_buf->len = len;

    return 0;
}/*}}}*/

